package com.mspbots.rule.queue.consumer;

import com.mspbots.cw.request.MessagesDTO;
import com.mspbots.rule.scheduled.service.MessagesSendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.mspbots.rule.config.RuleConfiguration.REDIS_KEY_PREFIX_TENANT;


/**
 * @ClassName com.mspbots.rule.queue.consumer.MessageConsumer
 * @Description TODO
 * @Author Jun
 * @Date 2019/8/28 17:42
 * @Version 1.0
 **/
@Slf4j
@Component
public class MessageConsumer {

    private Map<String, Boolean> sendingMap = new HashMap<>();

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Autowired
    private MessagesSendService messagesSendService;

    //    @RabbitListener(queues = "message.send")
//    public void onRule (MessagesDTO messagesDTO) {
//            messagesSendService.sendToTeams(messagesDTO);
//            if ("Ready".equalsIgnoreCase(messagesDTO.getForwardStatus())) {
//                messagesSendService.sendForward(messagesDTO);
//            }
//
//    }
//
//    @RabbitListener(queues = "message.sendForward")
    public void sendForward(MessagesDTO messagesDTO) {
        if ("Ready".equalsIgnoreCase(messagesDTO.getForwardStatus())) {
            messagesSendService.sendForward(messagesDTO);
        }
    }

    //    @RabbitListener(queues = "schedule.send")
    public void messageSend(List<MessagesDTO> messagesDTOList) {
        for (MessagesDTO messagesDTO : messagesDTOList) {
            if (sendingMap.get(messagesDTO.getTenantId() + "_" + messagesDTO.getRuleId()) == null) {
                String sending = stringRedisTemplate.opsForValue().get(REDIS_KEY_PREFIX_TENANT + messagesDTO.getTenantId() + ":" + messagesDTO.getRuleId() + "_sending");
                sendingMap.put(messagesDTO.getTenantId() + "_" + messagesDTO.getRuleId(), Boolean.valueOf(sending));
            }

            if (sendingMap.get(messagesDTO.getTenantId() + "_" + messagesDTO.getRuleId())) {
                messagesSendService.sendToTeams(messagesDTOList);
            }
        }
    }


}
